<template>
  <div>
    <el-drawer v-model="_isOpen" size="700" title="材料及工艺说明" :direction="'rtl'" modal-class="material-drawer">
      <template #header>
        <h4>材料及工艺说明</h4>
      </template>
      <template #default>
        <el-form :model="form" ref="formRef" :disabled="optionInfo.type === 'view'" label-width="auto" style="width: 100%">
          <el-form-item label="工艺标准说明" prop="standardDesc">
            <el-input
              v-model="form.standardDesc"
              type="textarea"
              placeholder="请输入工艺标准说明"
              maxlength="200"
              style="width: 100%"
            ></el-input>
            <!-- oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')" -->
          </el-form-item>
          <el-form-item label="优劣势说明" prop="shortcomingDesc">
            <el-input
              v-model="form.shortcomingDesc"
              type="textarea"
              placeholder="请输入优劣势说明"
              maxlength="200"
              style="width: 100%"
            ></el-input>
          </el-form-item>
          <el-form-item label="工艺标准图" prop="picIdLen">
            <div>
              <!-- 上传图片 -->
              <el-upload
                class="upload-demo upload-card"
                v-model:file-list="imgFileList"
                :disabled="FileList.length >= 9"
                ref="uploadImg"
                :show-file-list="true"
                multiple
                :limit="9"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="
                  (file, fileList) => {
                    handleAvatarChangeIcon(file, fileList);
                  }
                "
              >
                <div :class="{ notuse: FileList.length >= 9 ? true : false }">
                  <el-icon class="f24"><Plus /></el-icon>
                  <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
                </div>

                <template #file="{ file }">
                  <div>
                    <img v-show="file.img" class="el-upload-list__item-thumbnail" :src="file.img" alt="" />
                    <span v-show="!file.img" class="f30">
                      <el-icon><Loading /></el-icon>
                    </span>
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              <p class="f12 mt10" style="color: #86909c">只能上传jpg/png，且不超过10M,最大支持上传9张</p>
            </div>
          </el-form-item>
          <el-form-item label="工艺标准视频" prop="videoIdLen">
            <div>
              <!-- 上传图片 -->
              <el-upload
                class="upload-demo upload-card upload-video"
                v-model:file-list="videoListEdit"
                :disabled="videoList.length >= 6"
                ref="uploadVideo"
                :show-file-list="true"
                multiple
                :limit="8"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="
                  (file, fileList) => {
                    handleAvatarChangeIcon(file, fileList, 'video');
                  }
                "
              >
                <div :class="{ notuse: videoList.length >= 6 ? true : false }">
                  <el-icon class="f24"><Plus /></el-icon>
                  <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
                </div>

                <template #file="{ file }">
                  <div>
                    <!-- <img v-show="file.img" class="el-upload-list__item-thumbnail" :src="file.img" alt="" /> -->
                    <video controls style="width: 100%; height: 100%" v-if="file.video">
                      <source :src="file.video" type="video/mp4" />
                      对不起，您的浏览器不支持播放视频文件
                    </video>
                    <span v-show="!file.video" class="f30">
                      <el-icon><Loading /></el-icon>
                    </span>
                    <span class="el-upload-list__item-actions" v-show="optionInfo.type !== 'view'">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file, 'video')">
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
              <!-- avi/mov/mp4/wmv -->
              <p class="f12 mt10" style="color: #86909c">只能上传 mp4 文件格式，单个不超过200MB，最大支持6个</p>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="cancelClick">取消</el-button>
          <el-button v-if="optionInfo.type !== 'view'" type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import { updateCustomerSpaceQuota } from "@/apis/quote-price/following";

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        type: "add", //add edit view
        detail: {}
      };
    }
  }
});
const form = ref({});
const formRef = ref();
const _detail = ref({});

watch(
  () => props.optionInfo,
  val => {
    console.log("传递过来的公益材料说明", val);
    _detail.value = val.detail;
    form.value = {
      standardDesc: _detail.value.standardDesc,
      shortcomingDesc: _detail.value.shortcomingDesc
    };

    /**图片回显*/
    const imgList = [];
    const imgIds = _detail.value.picIds?.split(",") || [];
    const imgUrls = _detail.value.picUrls?.split(",") || [];
    for (let index in imgUrls) {
      imgList.push({
        url: imgUrls[index],
        img: imgUrls[index],
        uid: imgIds[index] || ""
      });
    }
    imgFileList.value = imgList;
    FileList.value = imgList;

    /**视频回显*/
    const _videoList = [];
    const videoIds = _detail.value.videoIds?.split(",") || [];
    const videoUrls = _detail.value.videoUrls?.split(",") || [];
    for (let index in videoUrls) {
      _videoList.push({
        url: videoUrls[index],
        video: videoUrls[index],
        uid: videoIds[index] || ""
      });
    }
    videoListEdit.value = _videoList;
    videoList.value = _videoList;
  },
  { deep: true, immediate: false }
);
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

/**确认修改 */
const submitFun = async () => {
  const params = {
    contentId: _detail.value.contentId,
    ...form.value,
    picIds: FileList.value.map(item => item.uid).join(","),
    picUrls: FileList.value.map(item => item.img).join(","),
    videoIds: videoList.value.map(item => item.uid).join(","),
    videoUrls: videoList.value.map(item => item.video).join(",")
  };
  await updateCustomerSpaceQuota(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "修改成功",
        type: "success"
      });
    }
  });
};

const reset = () => {
  form.value = {};
  formRef.value.resetFields();
  FileList.value = [];
  imgFileList.value = [];
  videoList.value = [];
  videoListEdit.value = [];
};

const cancelClick = () => {
  _isOpen.value = false;
  reset();
  // emit("changeAttr");
};
const confirmClick = async () => {
  try {
    await submitFun();
    _isOpen.value = false;
    reset();
    emit("submitOk");
  } catch (err) {
    console.log(err);
  }
};

defineExpose({});

//====================================图片上传========================================================================================
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { imgsUpload } from "@/apis/feedback";
import { ElMessage } from "element-plus";

const uploadImg = ref();
const uploadVideo = ref();
const FileList = ref([]); //商品图片list
const imgFileList = ref([]); //编辑时商品图片list
const videoList = ref([]); //商品视频list
const videoListEdit = ref([]); //编辑时商品视频list
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, _fileList);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传jpeg，jpg，png图片文件，大小不超过5M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      // const errorFile = _fileList.filter(
      //   item => !(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5
      // );
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    } else if (type === "video") {
      ElMessage({
        message: "只能上传视频文件，并且视频时长不超过45秒，大小不超过100M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "video/mp4") || item.raw.size > 1024 * 1024 * 100) {
          console.log(111, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          errorFile.push(item);
        } else {
          console.log(222, item, !item.raw.type === "video/mp4", item.raw.size > 1024 * 1024 * 200);
          successFile.push(item);
        }
      }
      // const errorFile = _fileList.filter(item => !(item.raw.type === "video/mp4"));
      for (let item of errorFile) {
        uploadVideo.value.handleRemove(item);
      }
    }
    fileList = successFile;
    if (successFile.length <= 0) return;
  }
  //   imgIsReady.value = false;
  if (type === "img") {
    FileList.value = fileList;

    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  } else {
    videoList.value = fileList;

    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.raw.type === "image/jpeg" || item.raw.type === "image/png") && item.raw.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      // console.log("视频的大小===", item.raw.size);
      if (!(item.raw.type === "video/mp4" && item.raw.size <= 1024 * 1024 * 200)) {
        flag = false;
      }
      //   if (item.raw.type === "video/mp4") {
      //     await getTimes(item.raw);
      //     // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
      //     if (!(videoTime.value <= 45)) {
      //       flag = false;
      //     }
      //   }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};

const handleRemove = (file, type = "img") => {
  console.log("移除===", file);
  if (type === "img") {
    uploadImg.value.handleRemove(file);
    FileList.value = FileList.value.filter(item => item.uid !== file.uid);
  } else {
    uploadVideo.value.handleRemove(file);
    videoList.value = videoList.value.filter(item => item.uid !== file.uid);
  }
};

/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  console.log(111111, option, option.file.name);
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      } else {
        item["video"] = res.fileUrl.split("?")[0];
        console.log("视频===", videoList.value);
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss">
.material-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    padding-bottom: 20px !important;
    margin-bottom: 0 !important;
    border-bottom: 1px solid #dcdfe6;
    h4 {
      font-weight: normal;
      position: relative;
      padding-left: 14px;
    }
  }
  .el-drawer__body {
    padding: 20 !important;
  }
  .el-drawer__footer {
    display: flex;
    justify-content: flex-end;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
    .el-button--primary {
      --el-button-bg-color: #424e66;
      border: none;
    }
    .el-button.el-button--info {
      --el-color-info: #f2f3f5;
      --el-color-white: #1d2129;
      &:hover {
        --el-button-hover-bg-color: #f2f3f5 !important;
        border-color: #f2f3f5 !important;
      }
    }
  }
}
</style>
<style lang="scss" scoped></style>
